<template>
  <div class="c-ph24 c-bg-sgray c-text-hidden" v-if="isShowContent">
    <div class="c-mt36" v-if="comeFrom == 1 || comeFrom == 2 || comeFrom == 4">
      <div v-for="(item,index) in applyArr" :key="index" :class="index == 0 ? '' : 'c-mt36'" class="c-br12 c-p c-ph24 c-bg-white">
        <div class="c-fs26 c-fc-xblack c-pv30 c-w100 c-flex-row c-justify-sb c-aligni-center">
          <div class="c-fc-sblack">身份选择:</div>
          <div class="c-flex-row">
            <popup-picker :themeColor="$getThemeColor()" title="" :data="comeFrom == 4 ? chainList : xhSfList" v-model="item.applyRole" :show.sync="item.showSelectRole" @on-hide="clickSelectRole($event, item, index)" :placeholder="'请选择身份'"></popup-picker>
          </div>
        </div>
        <div class="c-fs26 c-fc-xblack c-pv30 c-bd-b1 c-w100 c-flex-row c-justify-sb c-aligni-center">
          <div class="c-fc-sblack">区域选择:</div>
          <div class="c-flex-row c-flex-grow1 c-w0 c-justify-end">
            <x-address :themeColor="$getThemeColor()" :key="item.indexVal" title="" :show.sync="item.showAreaAddress" v-model="item.areaAddress" :list="applyArr[index].regionType == 1 || (applyArr[index].regionType == 42 && comeFrom == 4) ? provinceData : applyArr[index].regionType == 2 || (applyArr[index].regionType == 41 && comeFrom == 4) ? cityData : areaData" @on-hide="clickSelectArea($event, item, index)" @on-show="clickShowArea($event, item, index)" placeholder="请选择区域"></x-address>
          </div>
        </div>
        <p @click="delApply(index)" class="c-ww32 c-hh32 c-brp50 c-bg-mgray c-pa close-icon c-flex-row c-aligni-center c-justify-center">
          <i class="iconfont c-fc-white c-fs16">&#xe8fd;</i>
        </p>
      </div>
    </div>
    <div class="c-mt36" v-else>
      <div v-for="(item,index) in applyArr" :key="index" :class="index == 0 ? '' : 'c-mt36'" class="c-br12 c-p c-ph24 c-bg-white">
        <div class="c-fs26 c-fc-xblack c-pv30 c-bd-b1 c-w100 c-flex-row c-justify-sb c-aligni-center">
          <div class="c-fc-sblack">区域选择:</div>
          <div class="c-flex-row c-flex-grow1 c-w0 c-justify-end">
            <x-address :themeColor="$getThemeColor()" :key="item.indexVal" title="" :show.sync="item.showAreaAddress" v-model="item.areaAddress" :list="areaAddressData" @on-hide="clickSelectArea($event, item, index)" placeholder="请选择区域"></x-address>
          </div>
        </div>
        <div class="c-fs26 c-fc-xblack c-pv30 c-w100 c-flex-row c-justify-sb c-aligni-center">
          <div class="c-fc-sblack">身份选择:</div>
          <div class="c-flex-row">
            <popup-picker :themeColor="$getThemeColor()" title="" :data="sfList" v-model="item.applyRole" :show.sync="item.showSelectRole" @on-hide="clickSelectRole($event, item, index)" :placeholder="'请选择身份'"></popup-picker>
          </div>
        </div>
        <p @click="delApply(index)" class="c-ww32 c-hh32 c-brp50 c-bg-mgray c-pa close-icon c-flex-row c-aligni-center c-justify-center">
          <i class="iconfont c-fc-white c-fs16">&#xe8fd;</i>
        </p>
      </div>
    </div>

    <div class="c-fs28 theme-fc c-pv16 c-textAlign-c theme-bd1 c-br36 c-mt64" @click="addApply">
      <span>+ 增加申请</span>
    </div>
    <div class="c-fs28 c-fc-white c-pv16 c-textAlign-c theme-bg c-br36 c-mt30 c-mb30" @click="submitForm">
      <span>提交审核</span>
    </div>
    <!-- 申请进度 -->
    <div v-if="comeFrom != 4" @click="linkToApplyRecords" class="c-pf c-p-r24 c-p-b60 c-ww80 c-hh80 c-bg-white c-box-shadow7 c-fs20 c-fc-xblack c-flex-row c-justify-center c-aligni-center c-brp50">
      <span class="c-textAlign-c">申请<br>进度</span>
    </div>
  </div>
</template>
<script>
import { utilJs } from "@/utils/common.js";
import { XAddress, PopupPicker } from 'ckjrweb-mp-ui/src/components/index';
import validateVipType from './validateVipType'
let typeMap = {
  '正会长': 1,
  '副会长': 2
}
export default {
  name: 'applyNewAgent',
  mixins: [validateVipType],
  components: {
    XAddress,
    PopupPicker
  },
  data() {
    return {
      theme: localStorage.getItem("colorName") ? localStorage.getItem("colorName") : 'mb5_default',
      companyAuth: JSON.parse(localStorage.getItem("companyAuth")),
      areaAddressData: [],
      sfList: [['正会长', '副会长']],
      xhSfList: [['省代理', '市代理', '区代理']],
      chainList: [[]],
      addObj: {
        applyRole: [], // 选择的身份，数组（组件绑定的值）
        areaAddress: [], // 选择的地址，数组（组件绑定的值）
        role: '',
        provinceId: '',
        cityId: '',
        areaId: '',
        areaStatus: 0,
        showAreaAddress: false,
        showSelectRole: false,
        indexVal: 0
      },
      applyArr: [],
      isClick: false, // 防止重复点击
      level: [],
      comeFrom: 0, // 0胜者定制 1徐鸿定制 4链动2+1
      xhAddObj: {
        applyRole: [],
        areaAddress: [],
        regionId: "",
        regionType: "",
        beforeStatus: 0,
        indexVal: 0
      },
      provinceData: [],
      cityData: [],
      areaData: [],
      isFromAgent: 0,
      isShowContent: false,
      chainConf: ''
    }
  },
  computed: {
  },
  methods: {
    getChainConf() {
      return new Promise(function (resolve, reject) {
        utilJs.getMethod(global.apiurl + 'chain/getChainConf',
          res => {
            resolve(res);
          },
          failRes => {
            reject(failRes)
          }
        )
      })
    },
    initData() { // 初始化数据
      let url = this.comeFrom == 2 ? 'areaAgent/getAreas' : this.comeFrom == 4 ? 'chainUser/getChainAreas' : 'areaUser/getAreas';
      utilJs.getMethod(`${global.apiurl}${url}?level=${this.comeFrom == 4 ? 42 : 3}`, res => {
        this.areaAddressData = res;
      }, () => { })
      this.isShowContent = true;
    },
    getAreasList(index) {
      //获取地址 level参数 1获取到地址只有省 2省和市 3省市区
      if (this.level[index] == 1 && this.provinceData.length == 0) {
        let url = this.comeFrom == 2 ? 'areaAgent/getAreas' : this.comeFrom == 4 ? 'chainUser/getChainAreas' : 'xhAreaUser/getAreasList'
        utilJs.getMethod(`${global.apiurl}${url}?level=${this.comeFrom == 4 ? 42 : 1}`, res => {
          this.provinceData = res;
        })
      }
      if (this.level[index] == 2 && this.cityData.length == 0) {
        let url = this.comeFrom == 2 ? 'areaAgent/getAreas' : this.comeFrom == 4 ? 'chainUser/getChainAreas' : 'xhAreaUser/getAreasList'
        utilJs.getMethod(`${global.apiurl}${url}?level=${this.comeFrom == 4 ? 41 : 2}`, res => {
          this.cityData = res;
        })
      }
      if (this.level[index] == 3 && this.areaData.length == 0) {
        let url = this.comeFrom == 2 ? 'areaAgent/getAreas' : this.comeFrom == 4 ? 'chainUser/getChainAreas' : 'xhAreaUser/getAreasList'
        utilJs.getMethod(`${global.apiurl}${url}?level=${this.comeFrom == 4 ? 40 : 3}`, res => {
          this.areaData = res;
        })
      }
    },
    showTip(item) {
      this.$showCjToast({
        text: '当前区域已被选，请重新选择',
        type: "warn"
      });
      item.showAreaAddress = true;
      item.areaAddress = [];
    },
    clickSelectArea(val, item, index) { // 选择区域
      if (this.comeFrom == 1 || this.comeFrom == 2 || this.comeFrom == 4) { //徐鸿定制 || 旧版区域代理
        if (val) { // 点击确定
          if (item.areaAddress.length == 0) {
            return
          };
          if (this.level[index] == 1) {
            // 判断选中省 是否已经被选中
            if (this.provinceData.find(i => i.value == item.areaAddress[0]).status == 0) {
              this.showTip(item);
              return;
            }
          } else if (this.level[index] == 2) {
            if (this.cityData.find(i => i.value == item.areaAddress[1]).status == 0) {
              this.showTip(item);
              return;
            }
          } else if (this.level[index] == 3) {
            if (this.areaData.find(i => i.value == item.areaAddress[2]).status == 0) {
              this.showTip(item);
              return;
            }
          }
          if (item.regionType == 1 || (item.regionType == 42 && this.comeFrom == 4)) {
            this.applyArr[index].regionId = Number(item.areaAddress[0]);
          } else if (item.regionType == 2 || (item.regionType == 41 && this.comeFrom == 4)) {
            this.applyArr[index].regionId = Number(item.areaAddress[1]);
          } else if (item.regionType == 3 || (item.regionType == 40 && this.comeFrom == 4)) {
            this.applyArr[index].regionId = Number(item.areaAddress[2]);
          }
          if (this.applyArr.length > 1) {
            let timers = this.applyArr.filter((i, index) => {
              return i.regionId == item.regionId
            })
            if (timers.length > 1) {
              this.$showCjToast({
                text: '当前区域已被选，请重新选择',
                type: "warn"
              });
              item.showAreaAddress = false;
              item.areaAddress = [];
              this.applyArr[index].regionId = '';
            }
          }
        }
      } else {
        if (val) {
          if (item.areaAddress.length == 0) {
            return
          }
          this.sfList = [['正会长', '副会长']];
          var selectData = this.areaAddressData.find(i => i.value == item.areaAddress[2])
          this.applyArr[index].areaStatus = selectData.status || 0;
          // 区域status 0 可以 1 副会长可以 2 正会长可以 3 都不行
          if (item.role == 1) { // 已经选了正会长
            if (selectData.status == 3 || selectData.status == 1) {
              this.$showCjToast({
                text: '当前区域正会长已被选，请重新选择',
                type: "warn"
              });
              item.showAreaAddress = true
              return;
            }
          } else if (item.role == 2) { // 已经选了副会长
            if (selectData.status == 3 || selectData.status == 2) {
              this.$showCjToast({
                text: '当前区域副会长已被选，请重新选择',
                type: "warn"
              });
              item.showAreaAddress = true
              return;
            }
          }
          if (selectData.status == 3) {
            this.$showCjToast({
              text: '当前区域已被选，请重新选择',
              type: "warn"
            });
            item.showAreaAddress = true
            return;
          } else if (selectData.status == 1) { // 去掉正会长选项
            this.sfList = [['正会长(已被选)', '副会长']]
          } else if (selectData.status == 2) { // 去掉副会长选项
            this.sfList = [['正会长', '副会长(已被选)']]
          }
          this.applyArr[index].provinceId = item.areaAddress[0]
          this.applyArr[index].cityId = item.areaAddress[1]
          this.applyArr[index].areaId = item.areaAddress[2]
        }
      }
    },
    clickSelectRole(val, item, index) {
      if (this.comeFrom == 1 || this.comeFrom == 2 || this.comeFrom == 4) {
        if (val) {
          let role = item.applyRole[0];
          if (this.comeFrom == 4) {
            this.level[index] = role.indexOf(this.chainList[0][0]) > -1 ? 1 : role.indexOf(this.chainList[0][1]) > -1 ? 2 : 3;
          } else {
            this.level[index] = role.indexOf('省代理') > -1 ? 1 : role.indexOf('市代理') > -1 ? 2 : 3;
          }
          this.$nextTick(res => {
            if (this.applyArr[index].beforeStatus != item.regionType) {
              this.applyArr[index].areaAddress = [];
              this.applyArr[index].regionId = "";
            }
            this.applyArr[index].beforeStatus = item.regionType;
          })
          if (this.comeFrom == 4) {
            this.applyArr[index].regionType = this.level[index] == 1 ? 42 : this.level[index] == 2 ? 41 : 40;
          } else {
            this.applyArr[index].regionType = this.level[index];
          }
          this.getAreasList(index);
        }
      } else {
        if (val) { // 点击确定
          if (item.applyRole[0].includes('已被选')) {
            this.$showCjToast({
              text: '当前身份已被选，请重新选择',
              type: "warn"
            });
            item.showSelectRole = true
            item.applyRole = []
            return;
          }
          this.applyArr[index].role = typeMap[item.applyRole[0]];
        }
      }
    },
    clickShowArea($event, item, index) {
      if (this.applyArr[index].applyRole.length == 0) {
        this.$showCjToast({
          text: `请先选择身份`,
          type: "warn",
        });
        item.showAreaAddress = false;
      }
    },
    addApply() {
      var isValidate = true
      if (this.comeFrom == 0) {
        this.applyArr.forEach((el, index) => {
          if (el.areaStatus == 3 || (el.role == 1 && el.areaStatus == 1) || (el.role == 2 && el.areaStatus == 2)) { // 确认下是不是区域被选择的
            this.$showCjToast({
              text: `第${index + 1}个申请区域已被选，请重新选择`,
              type: "warn"
            });
            isValidate = false
          }
        })
      }
      if (!isValidate) { // 区域被选择的情况
        return;
      }
      if (!this.validateSubmitForm()) {
        return false;
      }
      if (this.comeFrom == 0) {
        if (this.applyArr.length > 0) { // 有申请的情况下
          var data = this.applyArr[this.applyArr.length - 1]
        // 将已经选择过的区域置为被选择的状态，防止重复申请
        // 区域status 0 可以 1 副会长可以 2 正会长可以 3 都不行
          this.areaAddressData.forEach(el => {
            if (el.value == data.areaId) {
              if (data.role == 1) { // 正会长
                // 若原来是都可选或者是副会长可以，那还是副会长可以  若不是，那说明是都不行选了 + '(副)'
                el.name = el.status == 0 || el.status == 1 ? el.label : el.label + '(已被选)';
                el.status = el.status == 0 ? 1 : (el.status == 1 ? el.status : 3); // 将这个改为副会长可选，若原来是 2 则改为3
              } else if (data.role == 2) { // 副会长
                el.name = el.status == 0 || el.status == 2 ? el.label : el.label + '(已被选)'; //  + '(正)'
                el.status = el.status == 0 ? 2 : (el.status == 2 ? el.status : 3); // 将这个改为正会长可选，若原来是 1 则改为3
              }
              return true
            }
          })
        }
        this.sfList = [['正会长', '副会长']] // 还原选项
        this.applyArr.push(JSON.parse(JSON.stringify(this.addObj)));
      } else if (this.comeFrom == 4) {
        this.applyArr.push(JSON.parse(JSON.stringify(this.addObj)));
      } else {
        this.applyArr.push(JSON.parse(JSON.stringify(this.xhAddObj)));
      }
      this.applyArr[this.applyArr.length - 1].indexVal = this.applyArr.length - 1
    },
    delApply(index) { // 删除申请
      // 把原来选择的区域状态再改回去
      // 区域status 0 可以 1 副会长可以 2 正会长可以 3 都不行
      var data = this.applyArr[index]
      if (this.comeFrom == 0) {
        this.areaAddressData.forEach(el => {
          if (el.value == data.areaId) {
            if (data.role == 1) { // 正会长
              // el.name = el.status == 1 ? el.label : el.label + '(正)'
              el.name = el.label;
              el.status = el.status == 1 ? 0 : 2; // 若原来是副会长可以，正会长删除之后就是都可以（0），若原来是 3 则改为2
            } else if (data.role == 2) { // 副会长
              // el.name = el.status == 2 ? el.label : el.label + '(副)'
              el.name = el.label;
              el.status = el.status == 2 ? 0 : 1; // 若原来是正会长可以，副会长删除之后就是都可以（0）若原来是 3 则改为1
            }
            return true
          }
        })
      }
      this.applyArr.splice(index, 1)
    },
    validateSubmitForm(type) { // 验证提交的合法性
      if (type == 'submit' && this.applyArr.length <= 0) {
        this.$showCjToast({
          text: '请至少填写一个申请',
          type: "warn"
        });
        return false;
      }
      var isTrue = true;
      this.applyArr.forEach((item, index) => {
        if ((this.comeFrom == 1 || this.comeFrom == 2 || this.comeFrom == 4) && !item.regionType) {
          this.$showCjToast({
            text: `第${index + 1}个申请的身份不能为空`,
            type: "warn"
          });
          isTrue = false;
          return false;
        }
        if ((this.comeFrom == 0 && !item.areaId) || ((this.comeFrom == 1 || this.comeFrom == 2 || this.comeFrom == 4) && !item.regionId)) {
          this.$showCjToast({
            text: `第${index + 1}个申请的区域不能为空`,
            type: "warn"
          });
          isTrue = false;
          return false;
        }
        if (this.comeFrom == 0 && !item.role) {
          this.$showCjToast({
            text: `第${index + 1}个申请的身份不能为空`,
            type: "warn"
          });
          isTrue = false;
          return false;
        }
      })
      if (!isTrue) {
        return false;
      }
      return true;
    },
    submitForm() {
      if (!this.validateSubmitForm('submit')) {
        return false;
      }
      if (this.isClick) {
        return false;
      }
      this.isClick = true
      var $this = this;
      let url = this.comeFrom == 1 ? 'xhAreaUser/areaUserApply' : this.comeFrom == 0 ? 'areaUser/areaUserApply' : this.comeFrom == 4 ? 'chainUser/applyChainCity' : 'areaAgent/applyAreaAgent';
      utilJs.postMethod(global.apiurl + url, { applyArr: this.applyArr }, res => {
        $this.isClick = false
        $this.$showCjToast({
          text: '申请成功',
          type: "success"
        });
        if (this.comeFrom == 1 || this.comeFrom == 4) {
          setTimeout(res => {
            this.$routerGo(this, "push", {
              path: '/homePage/newAreaUser/applyRecords',
              query: {
                comeFrom: this.comeFrom,
              }
            })
          }, 2000)
        } else {
          $this.linkToAreaAgent()
        }
      }, () => {
        $this.isClick = false
      })
    },
    linkToAreaAgent() {
      if (this.comeFrom == 1) {
        utilJs.getMethod(global.apiurl + "xhAreaUser/getWxAreaUserList", res => {
          if (Object.keys(res).length > 0) {
            this.goAreaAgent()
          } else {
            this.isShowContent = true;
          }
        })
      } else {
        this.goAreaAgent();
      }
    },
    goAreaAgent() {
      let url = this.comeFrom == 2 ? "/homePage/newAreaUser/oldAreaAgent" : "/homePage/newAreaUser/areaAgent";
      this.$routerGo(this, "replace", {
        path: url,
        query: {
          comeFrom: this.comeFrom,
        }
      })
    },
    linkToApplyRecords() {
      this.$routerGo(this, "push", {
        path: '/homePage/newAreaUser/applyRecords',
        query: {
          comeFrom: this.comeFrom,
        }
      })
    },
    isAreaUserIsApply() { // 验证是否申请过区域，申请过的跳转另一个页面
      let url = this.comeFrom == 2 ? 'areaAgent/areaAgentIsApply' : 'areaUser/areaUserIsApply'
      utilJs.getMethod(`${global.apiurl}${url}`, res => {
        if (res.isApply == 1) { // 申请过，跳转去申请过的页面
          this.linkToAreaAgent()
        } else { // 初始化数据
          if (this.comeFrom == 2 && this.isFromAgent != 1) {
            this.$routerGo(this, "replace", {
              path: "/homePage/agent/agentIndex",
              query: {
                fromType: "areaAgent",
              }
            })
          } else {
            this.initData();
          }
        }
      }, () => {

      })
    },
    //分享
    wechatShare: function () {
      let title = this.comeFrom == 1 ? '申请代理' : this.comeFrom == 1 ? '申请城市经理' : '申请会长';
      let shareImg = 'https://kposshzcdn.ckjr001.com/admin/material/9_material_admin/image/assets/i/wap/common/provider.png';
      let shareUrl = `${window.location.href.split("#")[0]}#${this.$route.path}?comeFrom=${this.comeFrom}&refereeId=${localStorage.getItem("userId")}`;
      let shareDesc = "点击查看详情";
      utilJs.wechatConfig(shareUrl, title, shareImg, shareDesc, function () { }, true);
    },
      //手机端分享
    appShare: function () {
      utilJs.appShareTrue("", "", "", "");
    }
  },
  activated() {
    this.comeFrom = this.$route.query.comeFrom;
    this.isFromAgent = this.$route.query.isFromAgent;
    this.chainList = [[]];
    this.isShowContent = false;
    if (this.comeFrom == 1 || this.comeFrom == 2) {
      setDocumentTitle('申请代理');// eslint-disable-line
    } else if (this.comeFrom == 4) {
      setDocumentTitle('申请城市经理');// eslint-disable-line
    } else {
      setDocumentTitle('申请会长');// eslint-disable-line
    };
    this.level = [];
    this.applyArr = [];
    if (this.comeFrom == 1 || this.comeFrom == 2 || this.comeFrom == 4) {
      this.provinceData = [];
      this.cityData = [];
      this.areaData = [];
      this.level.push(1);
    }
    if (this.comeFrom == 1) {
      this.applyArr.push(JSON.parse(JSON.stringify(this.xhAddObj)));
      if (!this.$route.query.from) {
        this.linkToAreaAgent();
      } else {
        this.initData()
      }
    } else if (this.comeFrom == 4) {
      this.getChainConf().then(res => {
        this.applyArr.push(JSON.parse(JSON.stringify(this.addObj)));
        this.chainConf = res;
        this.chainList[0].push(this.chainConf.arrTypeName['42'])
        this.chainList[0].push(this.chainConf.arrTypeName['41'])
        this.chainList[0].push(this.chainConf.arrTypeName['40'])
        this.initData();
      })
    } else {
      this.applyArr.push(JSON.parse(JSON.stringify(this.addObj)));
      if (!this.$route.query.from) {
        this.isAgentVipType().then(() => { // 验证服务商身份，不是的话跳转回个人中心
          this.isAreaUserIsApply();
        });
      } else { // 有from的直接让他申请，不用判断是否已经有记录了
        this.initData()
      }
    }
    this.wechatShare();
    window.scrollTo(0, 0); // 回到顶部
  },
  deactivated() {
    this.applyArr = [];
  }
}
</script>
<style scoped>
  .close-icon{
    right: -0.4rem;
    top: -0.4rem;
  }
</style>